package handler

import (
	"gofile/src/config"
	"gofile/src/util"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
)

// recursively delete a directory and its contents
func removeDir(path string) error {
	// get all files and directories in the path
	files, err := ioutil.ReadDir(path)
	if err != nil {
		return err
	}

	// loop through each file/directory and delete it
	for _, file := range files {
		filePath := filepath.Join(path, file.Name())
		if file.IsDir() {
			// recursively delete subdirectory
			err = removeDir(filePath)
			if err != nil {
				return err
			}
		} else {
			// delete file
			err = os.Remove(filePath)
			if err != nil {
				return err
			}
		}
	}

	// delete the directory itself
	err = os.Remove(path)
	if err != nil {
		return err
	}

	return nil
}

// delete a file or directory
func deleteFileOrDir(path string) error {
	// check if the path is a directory
	if fileInfo, err := os.Stat(path); err == nil && fileInfo.IsDir() {
		// recursively delete directory and its contents
		err = removeDir(path)
		if err != nil {
			return err
		}
	} else if err == nil {
		// path is a file, delete it
		err = os.Remove(path)
		if err != nil {
			return err
		}
	} else {
		// handle error
		return err
	}

	return nil
}

func DelFileHandler(w http.ResponseWriter, r *http.Request) {
	params := r.URL.Query()
	file := params.Get("file")
	myCfg := config.GetConfig()
	path := myCfg.File.Dir + file

	// call deleteFileOrDir with the path of the file to be deleted
	err := deleteFileOrDir(path)
	if err != nil {
		// handle error
		util.ProcessResult("删除文件"+path+"失败", err, w)
	} else {
		// file/directory deleted successfully
		util.ProcessResult("删除文件"+path+"成功", nil, w)
	}
}
